import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { ResponseHelper } from '../utils/response';
import { authenticateToken, requireAdmin } from '../middleware/auth';

const router: Router = express.Router();
const prisma = new PrismaClient();

/**
 * 获取统计数据
 * GET /api/v1/stats
 */
router.get('/', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    // 并行查询所有统计数据
    const [
      totalLocations,
      pendingLocations,
      approvedLocations,
      rejectedLocations,
      totalUsers,
      adminUsers,
      regularUsers,
      totalRatings,
      avgRatingResult
    ] = await Promise.all([
      // 地点统计
      prisma.location.count(),
      prisma.location.count({ where: { status: 'PENDING' } }),
      prisma.location.count({ where: { status: 'APPROVED' } }),
      prisma.location.count({ where: { status: 'REJECTED' } }),

      // 用户统计
      prisma.user.count(),
      prisma.user.count({ where: { role: 'ADMIN' } }),
      prisma.user.count({ where: { role: 'USER' } }),

      // 评分统计
      prisma.rating.count(),
      prisma.rating.aggregate({
        _avg: {
          score: true
        }
      })
    ]);

    const statsData = {
      totalLocations,
      pendingLocations,
      approvedLocations,
      rejectedLocations,
      totalUsers,
      adminUsers,
      regularUsers,
      totalRatings,
      averageScore: avgRatingResult._avg.score || 0
    };

    ResponseHelper.success(res, statsData, '统计数据获取成功');
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ResponseHelper.serverError(res, '获取统计数据失败', error);
  }
});

export default router;
